import { MailOutlined, } from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux';
import SubMenu from 'antd/lib/menu/SubMenu';
import './SideMenu.css'

const { Sider } = Layout;

function SideMenu(props) {
  const [menu, setMenu] = useState([]);
  useEffect(() => {
    axios.get("/rights?_embed=children").then(res => {
      // console.log(res.data);
      setMenu(res.data)
    })
  }, [])
  const routerClick = (e) => {
    // console.log('click ', e);
    props.history.push(e.key)
  };

  const { role: { rights } } = JSON.parse(localStorage.getItem('token'))

  const checkPagePermission = item => {
    return item.pagepermisson && rights.includes(item.key)
  }
  const renderMenu = (menuList) => {
    return menuList.map(item => {
      if (item.children?.length > 0 && checkPagePermission(item)) {
        return <SubMenu key={item.key} icon={<MailOutlined />} title={item.title}>
          {renderMenu(item.children)}
        </SubMenu>
      }
      return checkPagePermission(item) && <Menu.Item key={item.key} icon={<MailOutlined />} onClick={routerClick}>{item.title}</Menu.Item>
    })
  }

  // 默认选中的menu
  const selectedKeys = [props.location.pathname]
   // 默认展开的menu
  const defaultOpenKeys = ['/' + props.location.pathname.split('/')[1]]
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", "flexDirection": "column" }}>
        <div className="logo" >全球新闻发布管理系统</div>
        <div style={{flex:1,"overflow":"auto"}}>
          <Menu theme="dark" mode="inline" selectedKeys={selectedKeys} defaultOpenKeys={defaultOpenKeys} >
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>
    </Sider>
  )
}

const mapStateToProps = ({ CollapsedReducer: { isCollapsed } }) => {
  return {
    isCollapsed
  }
}

export default connect(mapStateToProps)(withRouter(SideMenu))